<!DOCTYPE html>
<html>
<head>
  <base href="/">
  <title>订单详情 - ToyqoMall</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <style>
    .order-detail-container {
      max-width: 1200px;
      margin: 20px auto;
      padding: 20px;
      background-color: #fff;
      border-radius: 8px;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    }

    .order-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding-bottom: 15px;
      border-bottom: 1px solid #eee;
      margin-bottom: 20px;
    }

    .order-status {
      padding: 5px 15px;
      border-radius: 20px;
      font-weight: bold;
      color: white;
    }

    .status-pending {
      background-color: #ff6b6b;
    }

    .status-processing {
      background-color: #ff9800;
    }

    .status-shipped {
      background-color: #2196F3;
    }

    .status-completed {
      background-color: #4CAF50;
    }

    .status-cancelled {
      background-color: #9e9e9e;
    }

    .order-info {
      display: flex;
      flex-wrap: wrap;
      margin-bottom: 20px;
    }

    .info-item {
      width: 33.33%;
      padding: 10px;
      box-sizing: border-box;
    }

    .info-label {
      font-weight: bold;
      color: #666;
      margin-bottom: 5px;
    }

    .info-value {
      font-size: 16px;
    }

    .order-products {
      margin-bottom: 20px;
    }

    .product-table {
      width: 100%;
      border-collapse: collapse;
    }

    .product-table th, .product-table td {
      padding: 12px 15px;
      text-align: left;
      border-bottom: 1px solid #eee;
    }

    .product-table th {
      background-color: #f9f9f9;
      font-weight: bold;
      color: #333;
    }

    .product-image {
      width: 80px;
      height: 80px;
      object-fit: cover;
      border-radius: 4px;
    }

    .product-name {
      font-weight: bold;
    }

    .address-section, .payment-section {
      margin-bottom: 20px;
      padding: 15px;
      background-color: #f9f9f9;
      border-radius: 8px;
    }

    .section-title {
      font-size: 18px;
      font-weight: bold;
      margin-bottom: 15px;
      color: #333;
      border-bottom: 1px solid #eee;
      padding-bottom: 10px;
    }

    .order-actions {
      display: flex;
      justify-content: flex-end;
      margin-top: 20px;
      padding-top: 20px;
      border-top: 1px solid #eee;
    }

    .btn-action {
      padding: 8px 20px;
      margin-left: 10px;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      font-weight: bold;
    }

    .btn-primary {
      background-color: #76aa6f;
      color: white;
    }

    .btn-secondary {
      background-color: #f0f0f0;
      color: #333;
    }

    .btn-danger {
      background-color: #f44336;
      color: white;
    }

    .order-timeline {
      margin: 30px 0;
      position: relative;
    }

    .timeline-track {
      position: absolute;
      top: 30px;
      left: 0;
      width: 100%;
      height: 4px;
      background-color: #eee;
      z-index: 1;
    }

    .timeline-progress {
      position: absolute;
      top: 30px;
      left: 0;
      height: 4px;
      background-color: #76aa6f;
      z-index: 2;
    }

    .timeline-steps {
      display: flex;
      justify-content: space-between;
      position: relative;
      z-index: 3;
    }

    .timeline-step {
      display: flex;
      flex-direction: column;
      align-items: center;
      width: 20%;
    }

    .step-icon {
      width: 30px;
      height: 30px;
      border-radius: 50%;
      background-color: #eee;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-bottom: 10px;
    }

    .step-active .step-icon {
      background-color: #76aa6f;
      color: white;
    }

    .step-label {
      text-align: center;
      font-size: 14px;
      color: #666;
    }

    .step-active .step-label {
      color: #76aa6f;
      font-weight: bold;
    }

    @media (max-width: 768px) {
      .info-item {
        width: 50%;
      }

      .product-table th:nth-child(3),
      .product-table td:nth-child(3) {
        display: none;
      }
    }

    @media (max-width: 576px) {
      .info-item {
        width: 100%;
      }

      .order-header {
        flex-direction: column;
        align-items: flex-start;
      }

      .order-status {
        margin-top: 10px;
      }

      .product-table th:nth-child(4),
      .product-table td:nth-child(4) {
        display: none;
      }
    }
  </style>
</head>
<!-- 保留原有的头部和样式 -->

<body>
<!-- 引入导航栏 -->

<div class="container">
  <div class="order-detail-container">
    <div class="order-header">
      <div>
        <h2>订单详情</h2>
        <p>订单号: <span id="order-code"></span></p>
      </div>
      <div class="order-status" id="order-status"></div>
    </div>

    <div class="order-timeline">
      <div class="timeline-track"></div>
      <div class="timeline-progress" id="timeline-progress"></div>
      <div class="timeline-steps">
        <div class="timeline-step" id="step-order">
          <div class="step-icon"><i class="fa fa-check"></i></div>
          <div class="step-label">下单</div>
        </div>
        <div class="timeline-step" id="step-payment">
          <div class="step-icon"><i class="fa fa-credit-card"></i></div>
          <div class="step-label">付款</div>
        </div>
        <div class="timeline-step" id="step-shipping">
          <div class="step-icon"><i class="fa fa-truck"></i></div>
          <div class="step-label">发货</div>
        </div>
        <div class="timeline-step" id="step-received">
          <div class="step-icon"><i class="fa fa-home"></i></div>
          <div class="step-label">收货</div>
        </div>
        <div class="timeline-step" id="step-review">
          <div class="step-icon"><i class="fa fa-star"></i></div>
          <div class="step-label">完成</div>
        </div>
      </div>
    </div>

    <div class="order-info">
      <div class="info-item">
        <div class="info-label">下单时间</div>
        <div class="info-value" id="order-time"></div>
      </div>
      <div class="info-item">
        <div class="info-label">付款时间</div>
        <div class="info-value" id="payment-time"></div>
      </div>
      <div class="info-item">
        <div class="info-label">付款方式</div>
        <div class="info-value" id="payment-method">在线支付</div>
      </div>
      <div class="info-item">
        <div class="info-label">订单总额</div>
        <div class="info-value" id="order-total" style="color: #ff6b6b; font-weight: bold;"></div>
      </div>
    </div>

    <div class="section-title">商品信息</div>
    <div class="order-products">
      <table class="product-table">
        <thead>
        <tr>
          <th>商品</th>
          <th>单价</th>
          <th>数量</th>
          <th>小计</th>
        </tr>
        </thead>
        <tbody id="product-list">
        <!-- 商品列表将通过JavaScript动态生成 -->
        </tbody>
      </table>
    </div>

    <div class="section-title">收货信息</div>
    <div class="address-section">
      <div id="receiver-info">
        <p><strong>收货人：</strong><span id="receiver-name"></span></p>
        <p><strong>联系电话：</strong><span id="receiver-phone"></span></p>
        <p><strong>收货地址：</strong><span id="receiver-address"></span></p>
      </div>
    </div>

   <!-- <div class="section-title">订单备注</div>
    <div class="payment-section">
      <p id="order-remark"></p>
    </div>-->

    <div class="order-actions">
      <button class="btn-action btn-secondary" onclick="window.history.back()">返回</button>
      <button class="btn-action btn-primary" id="btn-confirm-receipt" style="display: none;">确认收货</button>
    </div>
  </div>
</div>

<!-- 引入页脚 -->

<!-- 引入基础JS -->

<script src="layui/layui.all.js"></script>
<script>
  const $ = layui.$;

  // 获取URL中的订单ID参数
  const urlParams = new URLSearchParams(window.location.search);
  const orderId = urlParams.get('orderid');

  // 如果没有订单ID，返回上一页
  if (!orderId) {
    layer.msg('订单ID不能为空', {icon: 2});
    setTimeout(() => {
      window.history.back();
    }, 1500);
  }

  // 页面加载完成后获取订单数据
  $(document).ready(function() {
    loadOrderDetails(orderId);
  });

  // 加载订单详情
  function loadOrderDetails(orderId) {
    // 获取订单基本信息
    $.ajax({
      url: '/order/getorderbyid',
      type: 'GET',
      data: { orderid: orderId },
      success: function(orderResponse) {
        // 检查响应格式，处理直接返回订单对象的情况
        let order;
        if (orderResponse && orderResponse.code === 0 && orderResponse.data) {
          // 标准响应格式：{code: 0, data: {...}}
          order = orderResponse.data;
        } else if (orderResponse && orderResponse.orderid) {
          // 直接返回订单对象：{orderid: xxx, ...}
          order = orderResponse;
        } else {
          layer.msg('获取订单信息失败：无效的响应格式', {icon: 2});
          return;
        }

        // 填充订单基本信息
        $('#order-code').text(order.code || order.orderid);
        $('#order-total').text('¥' + (order.money ? parseFloat(order.money).toFixed(2) : '0.00'));
        $('#order-time').text(formatDate(order.addtime));
        $('#payment-time').text(order.paymenttime ? formatDate(order.paymenttime) : '未支付');
        /*$('#order-remark').text(order.remark || '无备注');*/

        // 设置订单状态
        updateOrderStatus(order.status);

        // 根据订单状态显示不同的按钮
        updateActionButtons(order.status, orderId);

        // 加载订单商品信息
        loadOrderItems(orderId);

        // 加载收货地址信息
        loadOrderAddress(orderId);
      },
      error: function(xhr, status, error) {
        console.error('获取订单信息失败:', error);
        layer.msg('获取订单信息失败: ' + error, {icon: 2});
      }
    });
  }



  // 添加日期格式化函数
  function formatDate(dateStr) {
    if (!dateStr) return '未知时间';

    try {
      // 处理不同格式的日期
      let date;
      if (typeof dateStr === 'string') {
        // 处理ISO格式的日期字符串
        date = new Date(dateStr);
      } else {
        // 处理其他格式
        date = new Date(dateStr);
      }

      // 检查日期是否有效
      if (isNaN(date.getTime())) {
        return dateStr;
      }

      // 格式化为本地日期时间字符串
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      });
    } catch (e) {
      console.error('日期格式化错误:', e);
      return dateStr;
    }
  }

  // 更新操作按钮
  function updateActionButtons(status, orderId) {
    const btnConfirmReceipt = $('#btn-confirm-receipt');
    const btnCancelOrder = $('#btn-cancel-order');
    const btnGoToPay = $('<button class="btn-action btn-primary" id="btn-go-to-pay">去支付</button>');

    // 默认隐藏所有按钮
    btnConfirmReceipt.hide();
    btnCancelOrder.hide();
    $('#btn-go-to-pay').remove(); // 移除之前可能存在的按钮

    // 根据状态显示不同按钮
    switch(status) {
      case 0: // 待付款
              // 添加去支付按钮
        btnGoToPay.insertBefore(btnCancelOrder);
        btnGoToPay.off('click').on('click', function() {
          goToPay(orderId);
        });

        btnCancelOrder.show().off('click').on('click', function() {
          cancelOrder(orderId);
        });
        break;
      case 2: // 待收货
        btnConfirmReceipt.show().off('click').on('click', function() {
          confirmReceipt(orderId);
        });
        break;
    }
  }

  // 去支付功能
  function goToPay(orderId) {
    if (!orderId) {
      layer.msg('订单ID不能为空');
      return;
    }
    // 跳转到支付页面
    window.location.href = `/shopping/payment?orderid=${orderId}`;
  }



  // 确认收货
  function confirmReceipt(orderId) {
    layer.confirm('确认已收到商品吗？', {icon: 3, title:'提示'}, function(index){
      $.ajax({
        url: '/order/confirm',
        type: 'POST',
        data: { orderid: orderId },
        success: function(response) {
          if (response && (response.code === 0 || response === 1 || response === "1")) {
            layer.msg('已确认收货', {icon: 1});
            setTimeout(() => {
              loadOrderDetails(orderId); // 重新加载订单信息
            }, 1500);
          } else {
            layer.msg('确认收货失败: ' + (response.msg || '请稍后重试'), {icon: 2});
          }
        },
        error: function(xhr, status, error) {
          layer.msg('确认收货失败: ' + error, {icon: 2});
        }
      });
      layer.close(index);
    });
  }

  // 加载订单商品信息
  function loadOrderItems(orderId) {
    $.ajax({
      url: '/orderinfo/list',
      type: 'GET',
      data: { orderid: orderId },
      success: function(response) {
        let items;
        if (response && response.code === 0 && response.data) {
          // 标准响应格式
          items = response.data;
        } else if (Array.isArray(response)) {
          // 直接返回数组
          items = response;
        } else {
          $('#product-list').html('<tr><td colspan="4" style="text-align: center;">暂无商品信息</td></tr>');
          return;
        }

        renderOrderItems(items);
      },
      error: function(xhr, status, error) {
        console.error('获取订单商品信息失败:', error);
        $('#product-list').html('<tr><td colspan="4" style="text-align: center;">获取商品信息失败</td></tr>');
      }
    });
  }

  // 加载收货地址信息
  function loadOrderAddress(orderId) {
    $.ajax({
      url: '/orderaddress/getorderaddressbyid',
      type: 'GET',
      data: { orderid: orderId },
      success: function(response) {
        let address;
        if (response && response.code === 0 && response.data) {
          // 标准响应格式
          if (Array.isArray(response.data) && response.data.length > 0) {
            address = response.data[0];
          } else {
            address = response.data;
          }
        } else if (Array.isArray(response) && response.length > 0) {
          // 直接返回数组
          address = response[0];
        } else if (response && response.orderaddressid) {
          // 直接返回单个对象
          address = response;
        } else {
          $('#receiver-info').html('<p>暂无收货信息</p>');
          return;
        }

        // 填充收货信息
        $('#receiver-name').text(address.nickname || address.name || '');
        $('#receiver-phone').text(address.phone || '');

        // 拼接完整地址
        const fullAddress = [
          address.province || '',
          address.city || '',
          address.state || '',
          address.address || ''
        ].filter(Boolean).join(' ');

        $('#receiver-address').text(fullAddress);
      },
      error: function(xhr, status, error) {
        console.error('获取收货地址信息失败:', error);
        $('#receiver-info').html('<p>获取收货信息失败</p>');
      }
    });
  }
  // 渲染订单商品列表
  function renderOrderItems(items) {
    const productList = $('#product-list');
    productList.empty();

    if (!items || items.length === 0) {
      productList.html('<tr><td colspan="4" style="text-align: center;">暂无商品信息</td></tr>');
      return;
    }

    items.forEach(item => {
      const subtotal = (item.price * item.count).toFixed(2);
      const html = `
        <tr>
          <td>
            <div style="display: flex; align-items: center;">
              <div style="margin-left: 15px;">
                <div class="product-name">${item.productname || '未知商品'}</div>
                <div style="color: #999; font-size: 14px;">${item.spec || ''}</div>
              </div>
            </div>
          </td>
          <td>¥${parseFloat(item.price).toFixed(2)}</td>
          <td>${item.count}</td>
          <td>¥${subtotal}</td>
        </tr>
      `;
      productList.append(html);
    });
  }




  // 更新订单状态显示
  function updateOrderStatus(status) {
    let statusText = '未知状态';
    let statusClass = '';
    let progressWidth = '0%';

    // 重置所有步骤
    $('.timeline-step').removeClass('step-active');

    switch(status) {
      case -1:
        statusText = '已失效';
        statusClass = 'status-cancelled';
        // 不激活任何步骤
        break;
      case 0:
        statusText = '待付款';
        statusClass = 'status-pending';
        progressWidth = '20%';
        $('#step-order').addClass('step-active');
        break;
      case 1:
        statusText = '待发货';
        statusClass = 'status-processing';
        progressWidth = '40%';
        $('#step-order, #step-payment').addClass('step-active');
        break;
      case 2:
        statusText = '待收货';
        statusClass = 'status-shipped';
        progressWidth = '60%';
        $('#step-order, #step-payment, #step-shipping').addClass('step-active');
        break;
      case 3:
        statusText = '已收货';
        statusClass = 'status-completed';
        progressWidth = '80%';
        $('#step-order, #step-payment, #step-shipping, #step-received').addClass('step-active');
        break;
      case 4:
        statusText = '已完成';
        statusClass = 'status-cancelled';
        progressWidth = '100%';
        $('#step-order, #step-payment, #step-shipping, #step-received,#step-review').addClass('step-active');
        // 不激活任何步骤
        break;
    }

    // 更新状态显示
    const statusElement = $('#order-status');
    statusElement.text(statusText);
    statusElement.removeClass('status-pending status-processing status-shipped status-completed status-cancelled');
    statusElement.addClass(statusClass);

    // 更新进度条
    $('#timeline-progress').css('width', progressWidth);
  }

  // 更新操作按钮







</script>
</body>
</html>